import React, { memo, useMemo } from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'
import { Icon } from '../../components'
import 'katex/dist/katex.min.css'

interface MarkdownRendererProps {
  content: string
  className?: string
  theme?: 'light' | 'dark'
}

export const MarkdownRenderer = memo<MarkdownRendererProps>(function MarkdownRenderer({ 
  content, 
  className = '', 
  theme = 'light' 
}) {
  // 缓存插件数组，避免每次渲染都重新创建
  const remarkPlugins = useMemo(() => [remarkGfm, remarkMath], [])
  const rehypePlugins = useMemo(() => [rehypeKatex], [])
  
  // 缓存组件配置，避免每次渲染都重新创建组件
  const components = useMemo(() => ({
    // 代码块高亮
    code({ inline, className, children, ...props }: any) {
      const match = /language-(\w+)/.exec(className || '')
      const language = match ? match[1] : ''
      
      if (!inline && language) {
        return (
          <div className="relative group">
            <div className="flex items-center justify-between bg-gray-800 text-gray-200 px-4 py-2 text-sm font-mono rounded-t-lg">
              <span>{language}</span>
              <button
                onClick={() => {
                  const codeText = String(children).replace(/\n$/, '')
                  navigator.clipboard.writeText(codeText).then(() => {
                    // 可以添加一个简单的视觉反馈
                    console.log('代码已复制到剪贴板')
                  }).catch(err => {
                    console.error('复制代码失败:', err)
                  })
                }}
                className="opacity-0 group-hover:opacity-100 transition-opacity duration-200 text-gray-400 hover:text-white"
                title="复制代码"
              >
                <Icon name="copy" className="w-4 h-4" />
              </button>
            </div>
            <SyntaxHighlighter
              style={theme === 'dark' ? oneDark : oneLight as any}
              language={language}
              PreTag="div"
              className="!mt-0 !rounded-t-none"
            >
              {String(children).replace(/\n$/, '')}
            </SyntaxHighlighter>
          </div>
        )
      }
      
      // 内联代码
      return (
        <code 
          className="bg-gray-100 text-red-600 px-1.5 py-0.5 rounded text-sm font-mono" 
          {...props}
        >
          {children}
        </code>
      )
    },
    
    // 标题样式
    h1: ({ children }: any) => (
      <h1 className="text-2xl font-bold text-gray-900 mb-4 pb-2 border-b border-gray-200">
        {children}
      </h1>
    ),
    h2: ({ children }: any) => (
      <h2 className="text-xl font-semibold text-gray-900 mb-3 mt-6">
        {children}
      </h2>
    ),
    h3: ({ children }: any) => (
      <h3 className="text-lg font-semibold text-gray-900 mb-2 mt-4">
        {children}
      </h3>
    ),
    h4: ({ children }: any) => (
      <h4 className="text-base font-semibold text-gray-900 mb-2 mt-3">
        {children}
      </h4>
    ),
    
    // 段落
    p: ({ children }: any) => (
      <p className="mb-4 leading-relaxed text-gray-800">
        {children}
      </p>
    ),
    
    // 列表
    ul: ({ children }: any) => (
      <ul className="list-disc list-outside pl-6 mb-4 space-y-1 text-gray-800">
        {children}
      </ul>
    ),
    ol: ({ children }: any) => (
      <ol className="list-decimal list-outside pl-6 mb-4 space-y-1 text-gray-800">
        {children}
      </ol>
    ),
    li: ({ children }: any) => (
      <li className="leading-relaxed">{children}</li>
    ),
    
    // 引用
    blockquote: ({ children }: any) => (
      <blockquote className="border-l-4 border-blue-500 pl-4 py-2 mb-4 bg-blue-50 text-gray-700 italic">
        {children}
      </blockquote>
    ),
    
    // 表格
    table: ({ children }: any) => (
      <div className="overflow-x-auto mb-4">
        <table className="min-w-full border border-gray-300 rounded-lg overflow-hidden">
          {children}
        </table>
      </div>
    ),
    thead: ({ children }: any) => (
      <thead className="bg-gray-50">{children}</thead>
    ),
    tbody: ({ children }: any) => (
      <tbody className="divide-y divide-gray-200">{children}</tbody>
    ),
    tr: ({ children }: any) => (
      <tr className="hover:bg-gray-50">{children}</tr>
    ),
    th: ({ children }: any) => (
      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b border-gray-300">
        {children}
      </th>
    ),
    td: ({ children }: any) => (
      <td className="px-4 py-3 text-sm text-gray-900 border-b border-gray-200">
        {children}
      </td>
    ),
    
    // 链接
    a: ({ children, href }: any) => (
      <a
        href={href}
        target="_blank"
        rel="noopener noreferrer"
        className="text-blue-600 hover:text-blue-800 underline font-medium"
      >
        {children}
      </a>
    ),
    
    // 强调
    strong: ({ children }: any) => (
      <strong className="font-semibold text-gray-900">{children}</strong>
    ),
    em: ({ children }: any) => (
      <em className="italic text-gray-700">{children}</em>
    ),
    
    // 删除线
    del: ({ children }: any) => (
      <del className="line-through text-gray-500">{children}</del>
    ),
    
    // 水平线
    hr: () => (
      <hr className="my-6 border-t border-gray-300" />
    ),
    
    // 图片
    img: ({ src, alt }: any) => (
      <img
        src={src}
        alt={alt}
        className="max-w-full h-auto rounded-lg shadow-sm mb-4"
      />
    )
  }), [theme])
  
  return (
    <div className={`markdown-content content-theme ${className}`}>
      <ReactMarkdown
        remarkPlugins={remarkPlugins}
        rehypePlugins={rehypePlugins}
        components={components}
      >
        {content}
      </ReactMarkdown>
    </div>
  )
})

export default MarkdownRenderer
